import router from '@/router';
import { useUserStore } from '@/stores'
import axios, { type Method } from 'axios'
import { showToast } from 'vant';

// 基础配置
const baseURL = 'https://consult-api.itheima.net/'
const instance = axios.create({
	baseURL,
	timeout:10000
})

// 请求拦截器 token令牌
instance.interceptors.request.use(
	(config) => {
		const store = useUserStore()
		if(store.user?.token && config.headers) {
			config.headers['Authorization'] = `Bearer ${store.user.token}`
		}
		return config
	},
	(err) => {
		Promise.reject(err)
	}
)

// 响应拦截器 10000 data 401
instance.interceptors.response.use(
	(res) => {
		if(res.data?.code !== 10000) {
			showToast(res.data?.messsage)
			return Promise.reject(res.data)
		}
		return res.data
	},
	(err) => {
		if(err.response.status === 401) {
			const store = useUserStore()
			store.delUser()
			router.push(`/login?returnUrl=${router.currentRoute.value.fullPath}`)
		}
		return Promise.reject(err)
	}
)

// 请求工具
type Data<T> = {
	code: number,
	message: string,
	data: T
}
const request = <T>(url: string, method: Method = 'GET', submitData?: object) => {
	return instance.request<T, Data<T>>({
		url,
		method,
		[method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
	})
}

// 返回
export {baseURL, instance, request}
